#include "projectfileconfig.h"

#include <QDateTime>
#include <QRandomGenerator>

projectFileConfig::projectFileConfig(QWidget *parent) : QWidget(parent)
{
}

projectFileConfig::projectFileConfig(Project_Path path, QWidget *parent) : QWidget(parent)
{
    this->load_proConfig(path);
}


void projectFileConfig::init_module_list()
{
    QDomNodeList list = this->proConfig.proModuleTable.childNodes();

    // 初始化 Module_List

    for (int n(0); n < list.count(); n++) {
        QDomElement module = list.at(n).toElement();

        if (module.nodeName() == "top")
            this->isMasterModuleExist = true;

        QFileInfo info(this->proConfig.proPath.proFilePath);
        QString path = info.path() + "/" + module.attribute("src");

        moduleFileConfig *mfc = new moduleFileConfig(this);
        mfc->init_Module_Data(path);

        this->module_list.insert(module.attribute("id"), mfc);

        qDebug() << "Init Module List " << path;
    }
}


bool projectFileConfig::load_proConfig(Project_Path path)
{
    this->proConfig.setProPath(path);
    qDebug() << "load_proConfig()" <<proConfig.getProFilePath();

    QFile file(proConfig.getProFilePath());

    if (!file.open(QFile::ReadOnly))
    {
        QMessageBox::information(this, "Error", "Can't Read Project File", QMessageBox::Ok);
        return false;
    }

    if (!this->proConfig.proDoc.setContent(&file))
    {
        QMessageBox::information(this, "Error", "Can't Read Project File", QMessageBox::Ok);
        return false;
    }

    file.close();

    // Root节点赋值
    this->proConfig.proRoot = this->proConfig.proDoc.documentElement();

    // Module Table节点赋值
    this->proConfig.proModuleTable = this->proConfig.proDoc.elementsByTagName("module_table").at(0).toElement();
    // 遍历 Module Table子节点，初始化Module
    // ....
    this->init_module_list();

    // Port关系表节点赋值
    this->proConfig.proPortConnexion = this->proConfig.proDoc.elementsByTagName("port_connexion").at(0).toElement();

    // Log节点赋值
    this->proConfig.proLog = this->proConfig.proDoc.elementsByTagName("log").at(0).toElement();

    return true;
}

void projectFileConfig::save_proConfig()
{
    QFile file(this->proConfig.getProFilePath());

    if (!file.open(QFile::ReadWrite | QFile::Truncate))
    {
        QMessageBox::information(this, "Error", "Can't Write Project Store File", QMessageBox::Ok);
        return;
    }

    QTextStream out(&file);
#if (QT_VERSION < QT_VERSION_CHECK(6,0,0))
    out.setCodec("utf-8");
#endif
    this->proConfig.proDoc.save(out, 4);
    file.close();
}

void projectFileConfig::recv_newModule(Module_Data data)
{
    qDebug() << "projectFileConfig new module" << data.get_module_name();

    moduleFileConfig *mfc = new moduleFileConfig(this);
    mfc->recv_newModule(this->proConfig.getProPath(), data);
//    connect(this, &projectFileConfig::send_newModule, mfc, &moduleFileConfig::recv_newModule);
//    emit this->send_newModule(this->proConfig.getProPath(), data);

    QString id = this->makeID();
    // Module列表增加新 Module
    this->module_list.insert(id, mfc);
    qDebug() << "After Insert Length : " << module_list.count();
    qDebug() << "get module_list module name : " << module_list.value(id)->get_module_name();

    QDomElement new_module;

    qDebug() << "master module exist : " << isMasterModuleExist;

    if (this->isMasterModuleExist)
    {
        new_module = this->proConfig.proDoc.createElement("module");  // 新建 Module
    }
    else
    {
        new_module = this->proConfig.proDoc.createElement("top"); // 新建 Master Module
        this->isMasterModuleExist = true;
    }

    new_module.setAttribute("id", id);
    //new_module.setAttribute("name", data.get_module_name());
    new_module.setAttribute("src", "module/" + data.get_module_name() + MODULE_END_FORMAT);

    // 将 Module节点加入 Module_Table
    this->proConfig.proModuleTable.appendChild(new_module);

    emit this->add_module(data, new_module);

    // test
    //.......
    this->save_proConfig();
}

inline QString projectFileConfig::makeMD5(QString content)
{
    return QCryptographicHash::hash(content.toLatin1(), QCryptographicHash::Md5).toHex();
}

inline QString projectFileConfig::makeID()
{
    return makeMD5(QString::number(QRandomGenerator::global()->generate()*2+5) + QDateTime::currentDateTime().toString("dddd yyyy-MM-dd hh:mm:ss.zzz"));  // 精确到毫秒
}

QDomNodeList projectFileConfig::get_module_tables()
{
    return this->proConfig.proDoc.elementsByTagName("module_table");
}

QString projectFileConfig::get_proName()
{
    return this->proConfig.getProName();
}

QString projectFileConfig::get_proPath()
{
    return this->proConfig.getProPath();
}


bool projectFileConfig::checkModule(QString module_name)
{
    auto list = this->module_list.values();

    for (int n(0); n < list.length(); n++) {
        if (list.at(n)->get_module_name() == module_name)
            return true;
    }

    return false;
}

Module_Data projectFileConfig::toModuleDataForID(QString ID)
{
    moduleFileConfig *mfc = module_list.value(ID);

    return mfc->get_module_data();
}
